package logic

import (
	"context"
	"fmt"
	"user_srv/models/mysql"
	"user_srv/models/redisinit"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	users := mysql.User{}
	err := users.UserInfo(in.Mobile)
	if err != nil {
		logx.Error("用户不存在")
		return nil, fmt.Errorf("用户不存在")
	}
	if users.ID == 0 {
		users.Mobile = in.Mobile
		users.Password = pkg.Md5(in.Password)
		err = users.Create()
		if err != nil {
			logx.Error("注册用户错误", err)
			return nil, fmt.Errorf("注册用户错误")
		}

	}
	get := redisinit.RedisClient.Get("sendSmslogin" + in.Mobile)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("获取短信信息错误")
	}
	if users.Password != pkg.Md5(in.Password) {
		logx.Error("密码不一致", err)
		return nil, fmt.Errorf("密码不一致")
	}
	return &user.UserLoginResponse{
		UserId: int64(users.ID),
	}, nil

}
